package com.hp.service;

import com.hp.dao.MedicalAdviceDao;
import com.hp.dao.RegistryDao;
import com.hp.entity.MedicalAdvice;
import com.hp.entity.Registry;
import com.hp.entity.dto.MedicalAdviceDto;
import com.hp.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;

public class MedicalAdviceService {
    private MedicalAdviceDao medicalAdviceDao=new MedicalAdviceDao();
    private RegistryDao registryDao=new RegistryDao();
    public MedicalAdviceDto getMedicalAdviceByRegistryId(int registryId) {
        return medicalAdviceDao.getMedicalAdviceByRegistryId(registryId);
    }

    public boolean updateMedicalAdviceById(MedicalAdvice medicalAdvice) {
        return medicalAdviceDao.updateMedicalAdvice(medicalAdvice);
    }

    public boolean insertMedicalAdvice(MedicalAdvice medicalAdvice){
        boolean result=false;
        Connection connection = JDBCUtils.getConnection();
        try {
            //设置手动提交
            connection.setAutoCommit(false);
            boolean bool1= medicalAdviceDao.insertMedicalAdvice(medicalAdvice);
            //更新挂号单状态
            Registry registry=new Registry();
            registry.setId(medicalAdvice.getRegistryId());
            //正在问诊,更新就诊时间和更新时间
            registry.setStatus(2);
            Date currentDate=new Date();
            registry.setUpdatedTime(currentDate);
            registry.setConsultationTime(currentDate);
            boolean bool2=registryDao.updateRegistryStatus(registry);
            result=bool1&&bool2;
            if(result){
               connection.commit();
            }
        } catch (Exception e) {
            //回滚
            try {
                connection.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }finally {
            try {
                connection.setAutoCommit(true);
                connection.close();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }
}
